import React, { useState, useEffect } from 'react'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'

const WangEditor = ({ changeContent, content, id }) => {
  const [editor, setEditor] = useState(null) // 存储 editor 实例
  const [html, setHtml] = useState('') // 编辑器内容

  useEffect(() => {
    if (id && content) {
      setHtml(content)
    }
  }, [])

  const toolbarConfig = {}
  const editorConfig = {
    placeholder: '请输入内容...',
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  const editorChange = (editor) => {
    setHtml(editor.getHtml())
    changeContent(editor.getHtml())
  }

  return (
    <>
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={editor => editorChange(editor)}
          mode="default"
          style={{ height: '500px', 'overflow': 'scroll' }}
        />
      </div>
    </>
  )
}

export default WangEditor
